//
//  HJFlutterController.m
//  KaiChat
//
//  Created by lx on 2024/3/21.
//

#import "HJFlutterController.h"
#import "HJFlutterManager.h"
#import "HJFlutterMethod.h"

#if LOADFLUTTER

#import <Flutter/Flutter.h>

#endif


@interface HJFlutterController ()

#if LOADFLUTTER

@property (nonatomic, strong) FlutterViewController *flutterViewController;

#endif

@property (nonatomic, strong) HJFlutterPageName name;

@end

@implementation HJFlutterController

- (HJFlutterController *)initWithName:(HJFlutterPageName)name {
    if (self = [super init]) {
        _name = name;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.fd_interactivePopDisabled = YES;
    
#if LOADFLUTTER
    
    HJFlutterManager.sharedManager.containController = self;

    FlutterViewController *flutterViewController = [[FlutterViewController alloc] initWithEngine:HJFlutterManager.sharedManager.mainEngine nibName:nil bundle:nil];
    _flutterViewController = flutterViewController;
    flutterViewController.view.frame = self.view.bounds;
    [self.view addSubview:flutterViewController.view];
    [self addChildViewController:flutterViewController];

#endif
    
    [self openPageWithName:self.name];
}

- (void)invokeWithName:(HJFlutterPageName)name arguments:(id _Nullable)arguments {
#if LOADFLUTTER
    FlutterMethodChannel *walletChannel = [FlutterMethodChannel methodChannelWithName:HJFlutterManager.sharedManager.channelName binaryMessenger:HJFlutterManager.sharedManager.mainEngine.binaryMessenger];
    [walletChannel invokeMethod:HJFlutterMethod.setBaseInfo arguments:[HJFlutterManager.sharedManager getFlutterMessageWithPage:name arguments:arguments] result:^(id  _Nullable result) {
        NSLog(@"result = %@", result);
    }];
#endif
}

- (void)openPageWithName:(HJFlutterPageName)name {
    
#if LOADFLUTTER
    
    FlutterMethodChannel *walletChannel = [FlutterMethodChannel methodChannelWithName:HJFlutterManager.sharedManager.channelName binaryMessenger:HJFlutterManager.sharedManager.mainEngine.binaryMessenger];
    [walletChannel invokeMethod:HJFlutterMethod.setBaseInfo arguments:[HJFlutterManager.sharedManager getFlutterMessageWithPage:name arguments:_arguments] result:^(id  _Nullable result) {
        NSLog(@"result = %@", result);
    }];
    
#endif
    
}

- (BOOL)hiddenNavigationBar {
    return YES;
}

- (void)dealloc {
    
#if LOADFLUTTER
    _flutterViewController = nil;
    HJFlutterManager.sharedManager.mainEngine.viewController = nil;
#endif
    NSLog(@"销毁flutterController, 和引擎置空");
    NSLog(@"%s", __func__);
}
 
@end
